﻿<script setup lang="ts" name="CropperAvatar">
import { propTypes } from '@/utils/propTypes'
import avatar from '@/assets/images/avatar.gif'
const { t } = useI18n() // 国际化
const { success } = useMessage()
const { getPrefixCls, variables } = useDesign()
const prefixCls = getPrefixCls('cropper-avatar')

const props = defineProps({
  width: propTypes.string.def('200px'),
  value: propTypes.string.def(''),
  title: propTypes.string.def(''),
  showBtn: propTypes.bool.def(true),
  btnText: propTypes.string.def('')
})

const emit = defineEmits(['update:value', 'change'])

const sourceValue = ref(props.value)

watchEffect(() => {
  sourceValue.value = props.value || ''
})

watch(
  () => sourceValue.value,
  (v: string) => {
    emit('update:value', v)
  }
)

const handleUploadSuccess = ({ source, data, filename }) => {
  sourceValue.value = source
  emit('change', { source, data, filename})
  success(t('cropper', 'uploadSuccess'))
}

const CropperModalRef = ref()

const open = () => {
  CropperModalRef.value.open()
}

const close = () => {
  CropperModalRef.value.close()
}

defineExpose({
  open,
  close
})
</script>

<template>
  <div :class="[variables.namespace + '-user-avatar']" @click="open()">
    <ElAvatar v-if="sourceValue" :src="sourceValue" alt="avatar" :class="[variables.namespace + '-img-circle', variables.namespace + '-img-lg']" />
    <ElAvatar v-if="!sourceValue" :src="avatar" alt="avatar" :class="[variables.namespace + '-img-circle', variables.namespace + '-img-lg']" />
    <ElButton v-if="showBtn" :class="`${prefixCls}-upload-btn`" @click="open()">
      {{ btnText ? btnText : t('cropper', 'selectImage') }}
    </ElButton>
    <CropperModal ref="CropperModalRef" :srcValue="sourceValue" :title="title" @uploadSuccess="handleUploadSuccess" />
  </div>
</template>

<style scoped lang="scss">
$prefix-cls: #{$namespace}-cropper-avatar;

.#{$prefix-cls} {
  display: inline-block;
  text-align: center;

  &-image-wrapper {
    overflow: hidden;
    cursor: pointer;
    border: 1px solid;
    border-radius: 50%;

    img {
      width: 100%;
    }
  }

  &-image-mask {
    position: absolute;
    width: inherit;
    height: inherit;
    cursor: pointer;
    background: rgb(0, 0, 0, 0.4);
    border: inherit;
    border-radius: inherit;
    opacity: 0;
    transition: opacity 0.4s;

    ::v-deep(svg) {
      margin: auto;
    }
  }

  &-image-mask:hover {
    opacity: 40;
  }

  &-upload-btn {
    margin: 10px auto;
  }
}

.#{$namespace}-user-avatar {
  position: relative;
  display: inline-block;
}

.#{$namespace}-img-circle {
  border-radius: 50%;
}

.#{$namespace}-img-lg {
  width: 120px;
  height: 120px;
}

.#{$namespace}-user-avatar:hover::after {
  position: absolute;
  inset: 0;
  font-size: 24px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-style: normal;
  line-height: 110px;
  color: #eee;
  cursor: pointer;
  background: rgb(0, 0, 0, 0.5);
  border-radius: 50%;
  content: '+';
}
</style>
